package code.example.service.admin;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.hibernate.Session;
import org.hibernate.cfg.Configuration;
import org.hibernate.cfg.Settings;
import org.hibernate.impl.SessionFactoryImpl;
import org.hibernate.tool.hbm2ddl.SchemaUpdate;
import org.springframework.core.io.ClassPathResource;

import com.googlecode.cswish.Config;
import com.googlecode.cswish.struts.hibernate.HibernateConfiguration;

/**
 * Manage DataBase
 * 
 * @author jerry.feng Date: 2008-10-24
 */
public class DBA {
	
	private static final Logger logger = Logger.getLogger(DBA.class);
	
	@Resource
	private HibernateConfiguration hibernateConfiguration;
	
	@Resource
	private Config config;

	public boolean init() {
		List<Configuration> configs = hibernateConfiguration
				.getConfigurations();

		for (Configuration config : configs) {
			config.setProperty("hibernate.hbm2ddl.auto", "create-drop");
			config.buildSessionFactory().openStatelessSession();
		}

		return true;
	}

	/**
	 * Update entity 
	 * 
	 * @param entityName
	 * @return
	 */
	public boolean update(String entityName) {
		List<Configuration> configs = hibernateConfiguration.getConfigurations();
		String resFile = null;
		try {
			if (configs.size() > 0) {
				Configuration config = configs.iterator().next();
				// for example: custom.hbm.xml
				resFile = this.config.getModelPackage() + entityName + ".hbm.xml";
				ClassPathResource mappingLocation = new ClassPathResource(resFile);
				config.addInputStream(mappingLocation.getInputStream());
				SessionFactoryImpl sessionFactory = (SessionFactoryImpl)hibernateConfiguration.getSessionFactory();
				Settings settings = sessionFactory.getSettings();
	
				if (settings.isAutoUpdateSchema()) {
					new SchemaUpdate(config, settings).execute(false, true);
				}
			}
		} catch (IOException ex) {
			logger.error("Can't find resource " + resFile, ex);
			
			return false;
		}
		return true;
	}
	
	public void save() {
		Session session = null;
		Map object = null;
		session.save(object);
		session.save("", object);
	}
}